package com.sftz.modules.minapp.teachActivityAnswer.service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Files;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.upload.TempFile;

import com.google.common.collect.Maps;
import com.sftz.assets.entities.InsCourseStructureEntity;
import com.sftz.assets.entities.ResourceEntity;
import com.sftz.assets.entities.teachactivity.TeachActivityAnswerEntity;
import com.sftz.assets.entities.teachactivity.TeachActivityAnswerFileEntity;
import com.sftz.assets.entities.teachactivity.TeachActivityApproveEntity;
import com.sftz.assets.entities.teachactivity.TeachActivityEntity;
import com.sftz.assets.entities.teachactivity.TeachActivityFileEntity;
import com.sftz.assets.entities.teachactivity.TeachActivityPostponeEntity;
import com.sftz.assets.enums.FileSizeEnum;
import com.sftz.assets.enums.FileTypeEnum;
import com.sftz.assets.enums.YesOrNoEnum;
import com.sftz.framework.service.aliyun.AliyunVideoDesc;
import com.sftz.framework.service.aliyun.AliyunVideoUploadService;
import com.sftz.framework.service.qiniu.QiniuDownloadService;
import com.sftz.modules.minapp.teachActivityAnswer.form.ActivityForm;
import com.sftz.modules.minapp.teachActivityAnswer.form.TeachAcFileForm;
import com.sftz.modules.minapp.user.cache.RedissionUserCache;
import com.uxuexi.core.common.util.DateUtil;
import com.uxuexi.core.common.util.EnumUtil;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.web.base.service.BaseService;

/**
 * @author   郝振斌
 * @Date	 2018年12月26日
 */
@IocBean
public class TeachActivityViewService extends BaseService<ResourceEntity> {

	private static final Log log = Logs.get();
	
	@Inject
	private QiniuDownloadService qiniuUploadService;
	
	@Inject
	private AliyunVideoUploadService aliyunVideoUploadService;

	public Object actiData(ActivityForm form) {
		
		Map<String, Object> map = Maps.newHashMap();
		Integer userId = RedissionUserCache.getUserId(form.getToken());
		TeachActivityEntity fetch = dbDao.fetch(TeachActivityEntity.class, Cnd.where("courseStruId", "=", form.getId()));
		Integer activityId = fetch.getId();
		Integer courseStruId = form.getId();
		InsCourseStructureEntity structureEntity = dbDao.fetch(InsCourseStructureEntity.class,
				Cnd.where("id", "=", courseStruId));
		String title = structureEntity.getName();
		//查询教学实践相关标题内容
		TeachActivityEntity teachInfo = dbDao.fetch(TeachActivityEntity.class, Cnd.where("id", "=", activityId));
		teachInfo.setTitle(title);

		//判断该教学实践是否延期
		TeachActivityPostponeEntity postpone = dbDao.fetch(TeachActivityPostponeEntity.class,
				Cnd.where("userId", "=", userId).and("activityId", "=", activityId));
		if (!Util.isEmpty(postpone)) {
			Date postDate = postpone.getPostDate();
			if (!Util.isEmpty(postDate)) {
				teachInfo.setEndDate(postDate);
			}
		}
		String fileSize = teachInfo.getFileSize();
		if (!Util.isEmpty(fileSize)) {
			String fileSizeStr = EnumUtil.getValue(FileSizeEnum.class, fileSize);
			map.put("fileSizeStr", fileSizeStr);
		}
		//存储教学实践过期状态
		Date endDate = teachInfo.getEndDate();
		Date nowDate = DateUtil.nowDate();
		if (!Util.isEmpty(endDate)) {
			if (endDate.getTime() < nowDate.getTime()) {
				map.put("pastSta", YesOrNoEnum.NO.intKey());//已经到截止时间，不可以作答
			} else {
				map.put("pastSta", YesOrNoEnum.YES.intKey());
			}
		}

		//查询教学实践相关文件
		List<TeachActivityFileEntity> activityFile = dbDao.query(TeachActivityFileEntity.class,
				Cnd.where("activityId", "=", activityId), null);
		//查询教学实践学生作答内容
		TeachActivityAnswerEntity answer = dbDao.fetch(TeachActivityAnswerEntity.class, Cnd
				.where("userId", "=", userId).and("activityId", "=", activityId));

		//查询教学实践老师审批内容
		if (!Util.isEmpty(answer)) {
			TeachActivityApproveEntity approve = dbDao.fetch(TeachActivityApproveEntity.class,
					Cnd.where("answerId", "=", answer.getId()).and("activityId", "=", activityId));
			map.put("approve", approve);
		}

		map.put("teachInfo", teachInfo);
		map.put("activityFile", activityFile);
		map.put("answer", answer);
		if (!Util.isEmpty(answer)) {
			List<TeachActivityAnswerFileEntity> answerFile = dbDao.query(TeachActivityAnswerFileEntity.class,
					Cnd.where("answerId", "=", answer.getId()), null);
			//查询教学实践学生上传文件
			map.put("answerFile", answerFile);
			map.put("ansFileSize", answerFile.size());
		}
		return map;
	}

	@Aop("txDb")
	public Object saveFile(TeachAcFileForm form) {
		TeachActivityAnswerFileEntity answerFile = new TeachActivityAnswerFileEntity();
		Integer userId = RedissionUserCache.getUserId(form.getToken());
		Integer activityId = form.getActivityId();
		String data = form.getData();
		Date nowDate = DateUtil.nowDate();
		Integer answerId = null;
		Map<String, Object> map = Maps.newHashMap();

		//查询当前用户是否是第一次作答
		TeachActivityAnswerEntity answerInfo = dbDao.fetch(TeachActivityAnswerEntity.class,
				Cnd.where("userId", "=", userId).and("activityId", "=", activityId));
		if (Util.isEmpty(answerInfo)) {
			TeachActivityAnswerEntity eny = new TeachActivityAnswerEntity();
			eny.setActivityId(activityId);
			eny.setContent(data);
			eny.setHandleDate(nowDate);
			eny.setUserId(userId);
			TeachActivityAnswerEntity insert = dbDao.insert(eny);
			answerId = insert.getId();
		} else {
			dbDao.update(TeachActivityAnswerEntity.class, Chain.make("content", data).add("handleDate", nowDate), Cnd
					.where("userId", "=", userId).and("activityId", "=", activityId));
			answerId = answerInfo.getId();
		}

		//存储学生-教学实践-上传的相关文件
		answerFile.setAnswerId(answerId);
		answerFile.setFileName(form.getResourceName());
		answerFile.setFileVal(form.getResourceValue());
		answerFile.setFileType(form.getResourceType());
		answerFile.setHandleDate(nowDate);
		answerFile = dbDao.insert(answerFile);
		map.put("answerFile", answerFile);

		List<TeachActivityAnswerFileEntity> answerFiles = dbDao.query(TeachActivityAnswerFileEntity.class,
				Cnd.where("answerId", "=", answerId), null);
		//查询教学实践学生上传文件
		map.put("answerFiles", answerFiles);

		return map;
	}

	public Object deleteFile(Integer fileId) {
		Map<String, Object> map = Maps.newHashMap();
		TeachActivityAnswerFileEntity fetch = dbDao.fetch(TeachActivityAnswerFileEntity.class,
				Cnd.where("id", "=", fileId));
		Integer answerId = fetch.getAnswerId();
		//删除
		dbDao.delete(TeachActivityAnswerFileEntity.class, fileId);
		List<TeachActivityAnswerFileEntity> answerFile = dbDao.query(TeachActivityAnswerFileEntity.class,
				Cnd.where("answerId", "=", answerId), null);
		//查询教学实践学生上传文件
		map.put("answerFile", answerFile);
		return map;
	}

	public Object uploadFile(TempFile f,TeachAcFileForm form) throws IOException {
		Map<String, Object> fileMsg = Maps.newHashMap();
		Integer resourceType = form.getResourceType();
		//获取输入流
		InputStream inputStream = f.getInputStream();
		//获取上传文件名
		File file = f.getFile();
		String fileName = file.getName();
		//fileMsg添加文件原名称
		fileMsg.put("fileName", fileName);
		//文件后缀
		String suffix = Files.getSuffix(fileName);
		suffix = suffix.substring(1);
		String resourceV = "";
		Integer resourceT = 0;
		if(resourceType == FileTypeEnum.VIDEO.intKey()){
			log.info("文件开始上传");
			AliyunVideoDesc vd = new AliyunVideoDesc();
			vd.setTitle(fileName);
			String videoId = aliyunVideoUploadService.uploadFile(vd, file.getAbsolutePath());
			fileMsg.put("fileUrl", videoId);
			fileMsg.put("fileType", FileTypeEnum.VIDEO.intKey());
			resourceV = videoId;
			resourceT = FileTypeEnum.VIDEO.intKey();
			//关闭输入流
			inputStream.close();
		}else if(resourceType == FileTypeEnum.AUDIO.intKey()){
			log.info("文件开始上传");
			String fileUrlOn = qiniuUploadService.uploadFile(inputStream, suffix, null);
			fileMsg.put("fileUrl", fileUrlOn);
			fileMsg.put("fileType", FileTypeEnum.AUDIO.intKey());
			resourceV = fileUrlOn;
			resourceT = FileTypeEnum.AUDIO.intKey();
			//关闭输入流
			inputStream.close();
		}else{
			log.info("文件开始上传");
			String fileUrlOn = qiniuUploadService.uploadFile(inputStream, suffix, null);
			fileMsg.put("fileUrl", fileUrlOn);
			fileMsg.put("fileType", FileTypeEnum.FILE.intKey());
			resourceV = fileUrlOn;
			resourceT = FileTypeEnum.FILE.intKey();
			//关闭输入流
			inputStream.close();
		}
		
		form.setResourceValue(resourceV);
		form.setResourceType(resourceT);
		String tname = form.getFileName();
		form.setResourceName(tname);
		
		return saveFile(form);
	}

}